<template>
  <div id="app">
    <!-- 聊天记录容器 -->
    <div class="chat-container">
      <div
        v-for="(message, index) in chatMessages"
        :key="index"
        :class="{ 'user-message': message.type === 'user', 'ai-message': message.type === 'ai' }"
      >
        {{ message.content }}
      </div>
    </div>
    <!-- 输入框和发送按钮 -->
    <div class="input-container">
      <input
        v-model="inputMessage"
        type="text"
        placeholder="请输入聊天内容"
        @keyup.enter="sendMessage"
      />
      <button @click="sendMessage">{{sendButtonLabel}}</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import requestChat from '../api/chat.js';

// 存储聊天记录
const chatMessages = ref([
  { type: 'ai', content: '欢迎使用聊天页面！有什么问题都可以问我。' }
]);
// 存储用户输入的消息
const inputMessage = ref('');
const sendButtonLabel = ref('发送');

// 发送消息的方法
const sendMessage = () => {
  if (inputMessage.value.trim() === '') return;
  sendButtonLabel.value = "发送中……"
  // 添加用户消息到聊天记录
  chatMessages.value.push({ type: 'user', content: inputMessage.value });
  // 发起聊天请求
  requestChat(inputMessage.value).then(res => {
    sendButtonLabel.value = "发送";
    inputMessage.value = '';
    chatMessages.value.push({type: 'ai', content: res.message});
  });
};
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.chat-container {
  height: 400px;
  border: 1px solid #ccc;
  overflow-y: auto;
  padding: 10px;
  text-align: left;
}

.user-message {
  text-align: right;
  background-color: #e1f5fe;
  padding: 8px;
  margin: 5px;
  border-radius: 5px;
}

.ai-message {
  text-align: left;
  background-color: #f1f8e9;
  padding: 8px;
  margin: 5px;
  border-radius: 5px;
}

.input-container {
  margin-top: 20px;
}

input {
  width: 300px;
  padding: 8px;
  margin-right: 10px;
}

button {
  padding: 8px 16px;
}
</style>